package com.example.shop.controller;

import com.alibaba.fastjson.JSON;
import com.example.shop.model.User;
import com.example.shop.service.UserService;
import com.example.shop.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UploadHeadController {
    @Autowired
    private UserService userService;

    @PostMapping("/uploadHead")
    public Map<String, Object> uploadHead(@RequestParam("file") MultipartFile file, @RequestParam("id") int id) throws IOException {
        Map<String, Object> map = new HashMap<>();
        System.err.println("文件名：" + file.getOriginalFilename());
        System.err.println("文件大小：" + file.getSize());
        //保存到本地
        String filename = file.getOriginalFilename();
        //设置路径
        User user = new User();
        user.setId(id);
        user.setHeadPic(filename);
        //将id换成文件名，替换掉上次上传的
        String fullPath = "D:\\Users\\富少辉\\Desktop\\springboot+vue\\springboot-vue-shop\\vue\\src\\img\\head_pic\\" + filename;
        File dest = new File(fullPath);
        file.transferTo(dest);
        System.err.println("上传到：" + dest.getAbsolutePath());
        int count = userService.setUserHeadPic(user);
        if (count > 0) {
            map.put("message", "成功");
        } else {
            map.put("message", "失败");
        }
        return map;
    }

    @RequestMapping("/download")
    public String download(String token) throws IOException {
        int userId = TokenUtil.getUserId(token);
        System.err.println(userId);
        String path = "D:\\Users\\富少辉\\Desktop\\springboot+vue\\springboot-vue-shop\\vue\\src\\img\\";
        FileInputStream fis = new FileInputStream(path + "2.jpg");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] bytes = new byte[fis.available()];
        bos.write(bytes);
        byte[] fileBytes = bos.toByteArray();
        //进行base64编码
//        BASE64Encoder encoder = new BASE64Encoder();
        Base64.Encoder encoder = Base64.getEncoder();
        String encodeString = encoder.encodeToString(fileBytes);
        System.err.println("encodeString = " + encodeString);
        Map<String, String> map = new HashMap<>();
        map.put("message", "成功");
        map.put("img", encodeString);
        return JSON.toJSONString(map);
    }
}
